<?php
namespace Admin\Controller;
use Think\Controller;
use Think\Page;
class TeacherController extends Controller
{

    function __construct()
    {
        parent::__construct();
        $this->check_auth(); //检查权限

        $sh_class = M("shclass");
        $sh_class_array = $sh_class->select();
        $sh_grade = M("grade");
        $sh_grade_array = $sh_grade->where("is_inschool=0") ->order("id DESC")->select();

        $this->assign('sh_class_array', $sh_class_array);
        $this->assign('sh_grade_array', $sh_grade_array);

    }

    public function showAll()
    {
        $stu_model = M('teacher');
        //导入分页助手类
        import('Org.Util.Page');
        $map['school_id'] = $_SESSION['school_id'];  //只能查看本校的
        $_REQUEST['sex']=$_REQUEST['sex'] ? $_REQUEST['sex'] : -1;
        $_REQUEST['zhicheng']=$_REQUEST['zhicheng'] ? $_REQUEST['zhicheng'] : -1;
        $_REQUEST['xueli']=$_REQUEST['xueli'] ? $_REQUEST['xueli'] : -1;

        $action = $_REQUEST['action'];

        $kw = $_REQUEST['kw'];
        $where['ID_number'] = array('like', "%{$kw}%");
        $where['name'] = array('like', "%{$kw}%");
        $where['mobile'] = array('like', "%{$kw}%");
        $where['xueke'] = array('like', "%{$kw}%");
        $where['renjiao_xueke'] = array('like', "%{$kw}%");
        $where['_logic'] = 'or';
        $map['_complex'] = $where;

        if ($_REQUEST['sex'] != -1) {
            $map['sex'] = $_REQUEST['sex'];
        }
        if ($_REQUEST['zhicheng'] != -1) {
            $map['zhicheng'] = $_REQUEST['zhicheng'];
        }
        if ($_REQUEST['xueli'] != -1) {
            $map['xueli'] = $_REQUEST['xueli'];
        }


        //var_dump($term);
        $total = $stu_model
            ->where($map)
            ->count();
        $page_size = 50;
        $page = new Page($total, $page_size);
        $page->setConfig("header", '个用户');
        $pageControl = $page->show();


       $stus = $stu_model
            ->where($map)
            ->order("id ASC")
            ->limit($page->firstRow,$page->listRows)
            ->select();
       // echo $stu_model->_sql();
      //  die();
        $pn = $_REQUEST['p'] ? $_REQUEST['p'] : 1;

        $fields = $_REQUEST['fields'];

        if ($action == "excel") {

                        if (!$fields) {
                            $fields = array("name", "sex", "ID_number",
                                "zhicheng", "zhiwu", "birthday", "in_date", "dishi","xianqu",
                                "canjia_date",
                                "renzhi_date",
                                "mobile",
                                "xueli",
                                "xueke",
                                "renjiao_xueke",
                                "QQ",
                                "wxid",
                                "email",
                                "zigezheng",
                                "jixujiaoyu",
                                "xueduan"
                            );
                        }
            $stus = $stu_model
                ->field(implode(",",$fields))
                ->where($map)
                ->order("id DESC")
                ->select();

            $excel = array(
                'dishi' => '地市',
                'xianqu' => '县区',
                'name' => '姓名',
                'sex' => '性别',
                'ID_number' => '身份证号',
                'zhicheng' => '职称',
                'zhiwu' => '职务',
                'birthday' => '生日',
                'in_date' => '进校日期',
                'canjia_date' => '参加工作时间',
                'renzhi_date' => '任职日间',
                'mobile' => '手机',
                'xueli' => '学历',
                'xueke' => '专业',
                'renjiao_xueke' => '任教学科',
                'QQ' => 'QQ',
                'wxid' => '微信ID',
                'email' => '电子邮件',
                'xueduan' => '学段',
                'zigezheng' => '教师资格证号',
                'jixujiaoyu' => '继续教育ID'
            );

            $excel_colspan = array("B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T","U","V");


            import("Org.Util.PHPExcel");
            import("Org.Util.PHPExcel.Writer.Excel5", '', '.php');
            import("Org.Util.PHPExcel.IOFactory", '', '.php');

            $objPHPExcel = new \PHPExcel();


// Set document properties
            $objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
                ->setLastModifiedBy("Maarten Balliauw")
                ->setTitle("Office 2007 XLSX Test Document")
                ->setSubject("Office 2007 XLSX Test Document")
                ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
                ->setKeywords("office 2007 openxml php")
                ->setCategory("Test result file");

            $objPHPExcel->setActiveSheetIndex(0);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', '序号');

            foreach ($fields as $kf => $vf) {
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($excel_colspan[$kf] . '1', $excel[$vf]);
            }


            foreach ($stus as $k => $v) {
                $num = $k + 2;
                $objPHPExcel->setActiveSheetIndex(0)
                    //Excel的第A列，uid是你查出数组的键值，下面以此类推
                    ->setCellValue('A' . $num, $num - 1);
                foreach ($fields as $kf => $vf) {
                    if (strstr($vf, 'number') || $vf=='zigezheng') {
                        $fgs = '  ';
                    } else {
                        $fgs = "";
                    }
                    $v = array_values($v);
                    $objPHPExcel->setActiveSheetIndex(0)->setCellValue($excel_colspan[$kf] . $num, $fgs . $v[$kf]);
                }
            }

            $objPHPExcel->getActiveSheet()->setTitle('教师信息');
            $objPHPExcel->setActiveSheetIndex(0);
            $filename = '教师信息包' . date('YmdHis');
            ob_end_clean();//清除缓冲区,避免乱码
            header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment;filename="' . $filename . '.xls"');
            header('Cache-Control: max-age=0');
            $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
            //   $objWriter = \PHPExcel_IOFactory::createReader('Excel5');
            //  $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
            $objWriter->save('php://output');
            exit;

        }


        $this->assign('stus', $stus);
        $this->assign('count', $total);
        $this->assign('page_title', "列表");
        $this->assign('pageControl', $pageControl);
        $this->display();

    }
       //实现学生修改功能
    public function update()
    {
        header("Content-Type:text/html;charset=utf-8");
        $stu = M('teacher');
        $id = $_GET['id'];
        if (!$_POST['name']) {
            $this->error('姓名不能为空！！');
        }

        $IDCard = $_POST['ID_number'];
        $tyear = intval(substr($IDCard, 6, 4));
        $tmonth = intval(substr($IDCard, 10, 2));
        $tday = intval(substr($IDCard, 12, 2));
        $_POST['birthday'] = $tyear . '-' . $tmonth . '-' . $tday;
        if ($id) {
            // $birth = strlen($idcard)==15 ? ('19' . substr($idcard, 6, 6)) : substr($idcard, 6, 8);
            // $sex = substr($idcard, (strlen($idcard)==15 ? -2 : -1), 1) % 2 ? '男' : '女';

            $stu_list = $stu->where("id=$id")->save($_POST);
            if ($stu_list) {
                $this->success('修改成功！！');
                $this->redirect('showAll');
            } else {
                $this->error('修改失败！！');
            }
        } else {
            $result = $stu->add($_POST);
            if ($result) {
                $this->success('添加成功！！');
                $this->redirect('showAll');
            } else {
                $this->error('添加失败！！');
            }
        }

        $this->redirect('showAll');//重定向到控制器的方法  display是本控制的方法

    }

    public function showUpdate()
    {
        $stu = M('teacher');
        $id = $_GET['id'];
        $stu_list = $stu->where("id=$id")->find();
        $this->assign('page_title', "修改");
        $this->assign('user_list', $stu_list);
        $this->display('update');
    }

    //实现学生删除功能
    public function del()
    {
        $stu = M('teacher');
        $id = $_GET['id'];
        $stu->where("id=$id")->delete();
        $this->redirect('showAll');//重定向到控制器的方法  display是本控制的方法
    }


    public function showAdd()
    {
        $this->assign('user_list', array('poor'=>0));
        $this->display('update');
    }

    public function upload()
    {
        ini_set('memory_limit', '1024M');
        if (!empty($_FILES)) {
            $config = array(
                'exts' => array('xlsx', 'xls'),
                'maxSize' => 3145728000,
                'rootPath' => "./Public/",
                'savePath' => 'Uploads/',
                'subName' => array('date', 'Ymd'),
            );
            $upload = new \Think\Upload($config);
            $info = $upload->upload();
            if (!$info) {
                $this->error($upload->getError());
            } else {//上传成功拼接获得上传文件的地址
                // $filename=ROOT.'/Public'.$info['excel']['savepath'].$info['excel']['savename'];
                $filename = $upload->rootPath . $info['files']['savepath'] . $info['files']['savename'];
                require_once THINK_PATH.'Library/Org/Util/PHPExcel/IOFactory.php';
                $reader =\PHPExcel_IOFactory::createReader('Excel5');
                $PHPExcel = $reader->load($filename);
                $sheet = $PHPExcel->getSheet(0); // 读取第一個工作表
                $highestRow = $sheet->getHighestRow(); // 取得总行数
                $highestColumm = $sheet->getHighestColumn(); // 取得总列数
                $stu_model = M('teacher');
                for ($row = 2; $row <= $highestRow; $row++){//行数是以第1行开始
                    $dataset = array();
                    for ($column = 'A'; $column <= $highestColumm; $column++) {//列数是以A列开始
                        $cell= $sheet->getCell($column.$row)->getValue();
                        if(is_object($cell))  $cell= $cell->__toString();
                        $dataset[] = $cell;
                    }



                    //查询是否存在
                   // var_dump($dataset);
                    $stus = $stu_model->where(array('ID_number'=>$dataset[7],'name'=>$dataset[4]))->find();

                    //如果姓名为空，全部跳出
                    if(!$dataset[0]){
                        break;
                    }

                    $IDCard = $dataset[7];//身份证号
                    $tyear = intval(substr($IDCard, 6, 4));
                    $tmonth = intval(substr($IDCard, 10, 2));
                    $tday = intval(substr($IDCard, 12, 2));
                    $birthday = $tyear . '-' . $tmonth . '-' . $tday;

                    $insert_data=array(
                        'name'=> $dataset[4],
                        'sex'=> $dataset[5],
                        'ID_number'=> $dataset[7],
                        'zhicheng'=> $dataset[9],
                        'zhiwu'=> $dataset[8],
                        'birthday'=> $birthday,
                        'dishi'=> $dataset[1],
                        'xianqu'=> $dataset[2],
                        'canjia_date'=> $dataset[14],
                        'mobile'=> $dataset[15],
                        'xueli'=> $dataset[10],
                        'xueke'=> $dataset[11],
                        'renjiao_xueke'=> $dataset[12],
                        'QQ'=> $dataset[17],
                        'zigezheng'=> $dataset[13],
                        'email'=> $dataset[16],
                        'xueduan'=> '小学'
                    );



                    if($stus){
                        //存在，更新学籍号
                        $stu_list = $stu_model->where("id=".$stus['id'])->save($insert_data);
                    }else{
                        $result = $stu_model->add($insert_data);
                    }

                }

                //数据导入成功之后的跳转操作
                $this->success('导入成功', U('Admin/Teacher/showAll'), 3);
            }
        }

    }





}